//
//  LSZReleaseDynamicVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/8/20.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZReleaseDynamicVC.h"

@interface LSZReleaseDynamicVC ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,LDImagePickerDelegate,UIGestureRecognizerDelegate>
@property(nonatomic,strong) UITableView * tableViewReleaseDynamic;
@property(nonatomic,assign) NSInteger numberPhoto;
@property(nonatomic,strong) LSZDynamicClassificationManager *  dynamicClassificationManager;
@property(nonatomic,strong) NSString * classificationString;//分类的名字
@property(nonatomic,strong) NSMutableArray * mutArrayImageView;//装图片的数组
@property(nonatomic,strong) NSMutableArray * mutArrayImageString;//装图片地址的数组


//上传的参数
@property(nonatomic,strong) NSString * classID;//分类的id
@property(nonatomic,strong) NSString * topicString;//主题


@end

@implementation LSZReleaseDynamicVC
-(void)viewWillAppear:(BOOL)animated
{
    NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:2 inSection:1]; //刷新第0段第2行
    [self.tableViewReleaseDynamic reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];
}
-(void)getData
{
    [LSZRequestResolutionDic publishDynamicCategorization:^(BOOL isok, NSString * string, LSZDynamicClassificationManager * manager) {
        if (isok == YES) {
            self.dynamicClassificationManager = manager;
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发布动态";
     
    self.numberPhoto = 0;
    self.classID = [[NSString alloc]init];
    self.topicString = [[NSString alloc]init];
    self.resource = [[NSString alloc]init];

    self.mutArrayImageView = [[NSMutableArray alloc]init];
    self.mutArrayImageString = [[NSMutableArray alloc]init];
    [self getData];
    [self.tableViewReleaseDynamic registerClass:[LSZChooseClassificationTableViewCell class] forCellReuseIdentifier:@"LSZChooseClassificationTableViewCell"];
    [self.tableViewReleaseDynamic registerClass:[LSZInputTopicTableViewCell class] forCellReuseIdentifier:@"LSZInputTopicTableViewCell"];
    [self.tableViewReleaseDynamic registerClass:[LSZInputTableViewCell class] forCellReuseIdentifier:@"LSZInputTableViewCell"];
    [self.tableViewReleaseDynamic registerClass:[LSZAddMusicTableViewCell class] forCellReuseIdentifier:@"LSZAddMusicTableViewCell"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ClickUploadPictures:) name:@"ClickUploadPictures" object:nil];

    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(onClickedOKbtn)];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}
#pragma mark - 删除的是那个图片
-(void)ClickUploadPictures:(NSNotification *)notification
{
    NSDictionary * dic = (NSDictionary *)notification.userInfo;
    int number = [dic[@"number"] intValue];//删的是第几个
    [self.mutArrayImageView removeObjectAtIndex:number];
    [self.mutArrayImageString removeObjectAtIndex:number];
    self.numberPhoto = self.numberPhoto - 1;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:1];
    [self.tableViewReleaseDynamic reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return 3;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.001;
    }else{
        return 10;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return [LSZSpecialPackaging initWithReturnsthesizeOf:45 :5];
    }else{
        if (indexPath.row == 0) {
            return 150;
        }else if (indexPath.row == 1){
            if(self.numberPhoto/3 == 3){
                return (self.numberPhoto/3) * ((ScreenWidth-40)/3+20);
            }else{
                return (self.numberPhoto/3+1) * ((ScreenWidth-40)/3+20);
            }
        }else{
            return 80;
        }
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            LSZChooseClassificationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZChooseClassificationTableViewCell" forIndexPath:indexPath];
            NSString * strStaus = @"*";
            NSString *str = [[NSString alloc]init];
            if ((NullStringjudgment(NSStr(self.cname))).length == 0 ) {
                if([cell.labelTitle.text isEqualToString:@"* 请选择动态的分类"]){
                    cell.labelTitle.textColor = lightColor;
                }else{
                    cell.labelTitle.textColor = titleColorLSZ;
                }
                NSString * string = NullStringjudgment(NSStr(self.classificationString));
                if (string.length >0) {
                    str = [NSString stringWithFormat:@"%@ 请选择动态的分类", self.classificationString];
                }else{
                    str = [NSString stringWithFormat:@"%@ 请选择动态的分类", strStaus];
                }
            }else{
                str = [NSString stringWithFormat:@"* %@",self.cname];
                cell.labelTitle.textColor = titleColorLSZ;
            }
            NSMutableAttributedString *attrDescribeStr = [[NSMutableAttributedString alloc] initWithString:str];
            [attrDescribeStr addAttribute:NSForegroundColorAttributeName
                                    value:[UIColor redColor]
                                    range:[str rangeOfString:strStaus]];
            cell.labelTitle.attributedText = attrDescribeStr;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }else{
            LSZInputTopicTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZInputTopicTableViewCell" forIndexPath:indexPath];

            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
            return cell;
        }
    }else{
        if (indexPath.row == 0) {
            LSZInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LSZInputTableViewCell" forIndexPath:indexPath];
            cell.textViewInput.delegate = self;
            if ((NullStringjudgment(NSStr(self.themeStr))).length != 0) {
                cell.textViewInput.text = [NSString stringWithFormat:@"#%@#",NSStr(self.themeStr)];
            }else{
                cell.textViewInput.text = @"请输入你要发布的内容!";
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
            return cell;
        }else if (indexPath.row == 1){
            LSZUploadPicturesTableViewCell * cell = [[LSZUploadPicturesTableViewCell alloc]initWithPhoneArray:self.numberPhoto :self.mutArrayImageView];
            [cell.imageViewPicture tapGesture:^(UIGestureRecognizer *ges) {
                if (cell.imageViewPicture.tag == self.numberPhoto+1) {
                    [self ModifyThePicture];
                }
            }];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        else{
            LSZAddMusicTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZAddMusicTableViewCell" forIndexPath:indexPath];
            if(![(NullStringjudgment(self.songName)) isEqualToString:@""]){
                cell.labelTitle.text = self.songName;
                if ([self.type isEqualToString:@"5"]) {
                    CGRect rect = cell.labelTitle.frame;
                    rect.origin.y = rect.origin.y+(cell.labelTitle.frame.size.height)/2;
                    cell.labelTitle.frame = rect;
                }
            }
            if(![(NullStringjudgment(self.authorOrAlbum)) isEqualToString:@""]){
                cell.labelAuthor.text = self.authorOrAlbum;
            }
            if(![(NullStringjudgment(self.cover_img)) isEqualToString:@""]){
                [cell.imageViewIcon sd_setImageWithURL:[NSURL URLWithString:self.cover_img] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if ((NullStringjudgment(NSStr(self.cname))).length == 0 && indexPath.row == 0) {
            [self clickOneRow];
        }

    }else{
        if (indexPath.row == 2) {
            LSZAudioRViewController * vc = [[LSZAudioRViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}
-(void)clickOneRow
{
    __weak typeof(self) weakSelf = self;
    [weakSelf keyboardWhereabouts];
    DLPickerView *pickerView = [[DLPickerView alloc] initWithDataSource:self.dynamicClassificationManager.mutNameArray withSelectedItem:nil withSelectedBlock:^(id selectedItem){
         LSZChooseClassificationTableViewCell * cell = (LSZChooseClassificationTableViewCell *)[weakSelf.tableViewReleaseDynamic cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
        self.classificationString = [NSString stringWithFormat:@"%@",selectedItem];
        for (int i = 0; i<self.dynamicClassificationManager.mutMgArray.count; i++) {
            LSZDynamicClassificationMg * mg = nil;
            mg = self.dynamicClassificationManager.mutMgArray[i];
            if ([mg.name isEqualToString:selectedItem]) {
                self.classID = mg.id_id;
            }
        }
        NSString * strStaus = @"*";
        NSString *str = [NSString stringWithFormat:@"%@ %@", strStaus,self.classificationString];
        NSMutableAttributedString *attrDescribeStr = [[NSMutableAttributedString alloc] initWithString:str];
        [attrDescribeStr addAttribute:NSForegroundColorAttributeName
                                value:[UIColor redColor]
                                range:[str rangeOfString:strStaus]];
        cell.labelTitle.attributedText = attrDescribeStr;
    }];
    [pickerView show];
}
#pragma mark - 发布按钮的点击事件
-(void)onClickedOKbtn
{
    __weak typeof(self) weakSelf = self;
//    LSZInputTopicTableViewCell * cellTwo = (LSZInputTopicTableViewCell *)[weakSelf.tableViewReleaseDynamic cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1  inSection:0]];
    LSZInputTableViewCell * cellThree = (LSZInputTableViewCell *)[weakSelf.tableViewReleaseDynamic cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:1]];
//    if (cellTwo.textFieldTopic.text.length == 0) {
//        [self initWithtring:@"请填写你动态的话题"];
//        return;
//    }
    NSString * strClass = [[NSString alloc]init];//主题

    NSString * strControl = [[NSString alloc]init];
    if ((NullStringjudgment(NSStr(self.themeStr))).length != 0) {
        strClass = self.cname;
        self.classID = self.kind;
       strControl = [cellThree.textViewInput.text substringFromIndex:(self.themeStr.length+2)];//截取掉下标3之后的字符串
        if (strControl.length == 0 ) {
            strControl = @"";
        }
    }else{
        if (self.cname.length != 0) {
            strClass = self.cname;
            self.classID = self.kind;
        }else{
            strClass = NullStringjudgment(NSStr(self.classificationString));
        }
        if (strClass.length == 0) {
            [self initWithtring:@"请选择动态的主题"];
            return;
        }
        if ([cellThree.textViewInput.text isEqualToString:@"请输入你要发布的内容!"]) {
            strControl = @"";
        }else{
            strControl = cellThree.textViewInput.text;
        }
    }
    NSString * string = [[NSString alloc]init];
    for (int i = 0; i <self.mutArrayImageString.count; i++) {
        if (i == 0) {
               string = [NSString stringWithFormat:@"%@",self.mutArrayImageString[i]];
        }else{
            string = [NSString stringWithFormat:@"%@,%@",string,self.mutArrayImageString[i]];
        }
    }
    NSString * type = NullStringjudgment(NSStr(self.type));
    //上传图片
    [LSZRequestResolutionDic uploadFilesOfVariousTypes:self.mutArrayImageView filePath:self.mutArrayImageString :^(BOOL isOK, NSString * string, LSZFileUploadGenericManager * manager) {
        if(isOK == YES){
            if ((NullStringjudgment(NSStr(self.theme))).length != 0) {
                self.topicString = self.theme;
            }
            NSString * resource = NullStringjudgment(NSStr(self.resource));
            [LSZRequestData releaseTheDynamic:self.classID type:type resource:resource  title:strClass content:strControl theme:self.topicString images:manager.idString :^(BOOL isOk, NSString * Str, NSDictionary * dicTion) {
                [self initWithtring:Str];
                if (isOK == YES) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        // 刷新表格  和结束刷新
                        if ([Str rangeOfString:@"成功"].location != NSNotFound) {
                            [self.navigationController popViewControllerAnimated:YES];
                        }
                    });
                }
            }];
        }else{
            [self initWithtring:string];
        }
    }];
}
#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.textColor = [UIColor grayColor];
        if ((NullStringjudgment(NSStr(self.themeStr))).length == 0) {
            textView.text = @"请输入你要发布的内容!";
        }else{
            textView.text = [NSString stringWithFormat:@"#%@#",NSStr(self.themeStr)];
        }
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ((NullStringjudgment(NSStr(self.themeStr))).length == 0) {
        if([textView.text isEqualToString:@"请输入你要发布的内容!"]){
            textView.text=@"";
            textView.textColor=[UIColor blackColor];
        }
    }
}
//这个函数的最后一个参数text代表你每次输入的的那个字，所以：
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self.view endEditing:YES];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    if ((NullStringjudgment(NSStr(self.themeStr))).length != 0) {
        if (range.location < self.themeStr.length+2){
            return NO;
        }
    }
    return YES;
}
#pragma mark - 修改头像
-(void)ModifyThePicture
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *showAllInfoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf initWithPhoneFromThePhotoAlbum];
    }];
    UIAlertAction *pickAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf initWithPhoneTakingpictures];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [actionSheetController addAction:cancelAction];
    [actionSheetController addAction:pickAction];
    [actionSheetController addAction:showAllInfoAction];
    [weakSelf presentViewController:actionSheetController animated:YES completion:nil];
}
#pragma mark - 拍照
-(void)initWithPhoneTakingpictures
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相机
        sourceType = UIImagePickerControllerSourceTypeCamera;
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            [self initWithtring:@"摄像头访问受限,请打开摄像头允许拍摄!"];
            return;
        }
    }
    else {
        [self initWithtring:@"此设备没有摄像功能!"];
        return;
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:0   InViewController:self Scale:1];
}
#pragma mark - 从相册里面查找
-(void)initWithPhoneFromThePhotoAlbum
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相册//来自图库
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    else {
        //来自相册
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:1   InViewController:self Scale:1];
}
- (void)imagePicker:(LDImagePicker *)imagePicker didFinished:(UIImage *)editedImage{
    __weak typeof(self) weakSelf = self;
    LSZUploadPicturesTableViewCell * cell = (LSZUploadPicturesTableViewCell *)[weakSelf.tableViewReleaseDynamic cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1  inSection:1]];
    cell.imageViewPicture.image = editedImage;
    [self.mutArrayImageView addObject:editedImage];
    UIImage *imagestr = editedImage;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@""]];   // 保存文件的名称
    [self.mutArrayImageString addObject:filePath];
//    BOOL result = [UIImagePNGRepresentation(imagestr)writeToFile: filePath    atomically:YES]; // 保存成功会返回YES
    self.numberPhoto = self.numberPhoto + 1;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:1];
    [self.tableViewReleaseDynamic reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

}
-(void)keyboardWhereabouts
{
    [self.view endEditing:YES];
}
- (void)imagePickerDidCancel:(LDImagePicker *)imagePicker{

}
-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizershouldReceiveTouch:(UITouch *)touch
{
    if([NSStringFromClass([touch.view class])isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}
#pragma mark - UITextViewDelegate
-(UITableView *)tableViewReleaseDynamic
{
    if (_tableViewReleaseDynamic == nil) {
        _tableViewReleaseDynamic = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
        _tableViewReleaseDynamic.delegate = self;
        _tableViewReleaseDynamic.dataSource = self;
        _tableViewReleaseDynamic.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
        _tableViewReleaseDynamic.estimatedRowHeight =0;
        _tableViewReleaseDynamic.estimatedSectionFooterHeight =0;
        _tableViewReleaseDynamic.estimatedSectionHeaderHeight =0;
        [self.view addSubview:_tableViewReleaseDynamic];
    }
    return _tableViewReleaseDynamic;
}


@end
